package cn.stylefeng.guns.modular.usr.service.impl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.usr.entity.Favor;
import cn.stylefeng.guns.modular.usr.mapper.FavorMapper;
import cn.stylefeng.guns.modular.usr.model.params.FavorParam;
import cn.stylefeng.guns.modular.usr.model.result.FavorResult;
import cn.stylefeng.guns.modular.usr.service.FavorService;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;

/**
 * <p>
 * 新闻收藏 服务实现类
 * </p>
 *
 * @author
 * @since 2019-12-17
 */
@Service
public class FavorServiceImpl extends ServiceImpl<FavorMapper, Favor> implements FavorService {

    @Override
    public void add(FavorParam param) {
        Favor entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(FavorParam param) {
        this.removeById(getKey(param));
    }

    @Override
    public void update(FavorParam param) {
        Favor oldEntity = getOldEntity(param);
        Favor newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public FavorResult findBySpec(FavorParam param) {
        QueryWrapper<Favor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("open_id", param.getOpenId()).eq("news_id", param.getNewsId());
        Favor favor = this.getOne(queryWrapper);
        FavorResult favorResult = new FavorResult();
        ToolUtil.copyProperties(favor, favorResult);
        return favorResult;
    }

    @Override
    public List<FavorResult> findListBySpec(FavorParam param) {
        return this.baseMapper.customList(param);
    }

    @Override
    public LayuiPageInfo findPageBySpec(FavorParam param) {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    private Serializable getKey(FavorParam param) {
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private Favor getOldEntity(FavorParam param) {
        return this.getById(getKey(param));
    }

    private Favor getEntity(FavorParam param) {
        Favor entity = new Favor();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

}
